﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Browser;

namespace HDViewSL
{
	/// <summary>
	/// The main application.
	/// </summary>
	public partial class App : Application
	{
		/// <summary>
		/// Constructs a new application.
		/// </summary>
		public App()
		{
			this.Startup += this.Application_Startup;
			this.UnhandledException += this.Application_UnhandledException;

			this.InitializeComponent();
		}

		/// <summary>
		/// Handles the application startup event.
		/// </summary>
		private void Application_Startup(object sender, StartupEventArgs e)
		{
			// Create a page.
			var page = new Page();
			page.BackgroundColor = this.Host.Background;

			// Create the communication channel between Javascript and HD View SL.
			var settings = new HDViewSettings(page);
			HtmlPage.RegisterScriptableObject("settings", settings);

			// Process any initialization parameters that are passed in from the HTML page.
			// Get the full-resolution image width.
			var width = GetIntParameter(e.InitParams, "width");
			if (width != null)
			{
				page.ImageWidth = width.Value;
			}

			// Get the full-resolution image height.
			var height = GetIntParameter(e.InitParams, "height");
			if (height != null)
			{
				page.ImageHeight = height.Value;
			}

			// Get the display mode.
			var displayMode = GetEnumParameter<DisplayMode>(e.InitParams, "displayMode");
			if (displayMode != null)
			{
				page.DisplayMode = displayMode.Value;
			}

			// Get the source URI.
			string source;
			if (e.InitParams.TryGetValue("source", out source))
			{
				page.Source = source;
			}
			
			// Set the application's root visual to the page instance.
			this.RootVisual = page;

			// Invoke the "initialization completed" callback.
			string initializationCompleted;
			if (e.InitParams.TryGetValue("InitializationCompleted", out initializationCompleted))
			{
				var handler = HtmlPage.Window.GetProperty(initializationCompleted) as ScriptObject;
				if (handler != null)
				{
					try
					{
						handler.InvokeSelf();
					}
					catch
					{
					}
				}
			}
		}

		/// <summary>
		/// Handles the application's UnhandledException event.
		/// </summary>
		private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
		{
			// If the app is running outside of the debugger then report the exception using
			// the browser's exception mechanism. On IE this will display it a yellow alert 
			// icon in the status bar and Firefox will display a script error.
			if (!System.Diagnostics.Debugger.IsAttached)
			{

				// NOTE: This will allow the application to continue running after an exception has been thrown
				// but not handled. 
				// For production applications this error handling should be replaced with something that will 
				// report the error to the website and stop the application.
				e.Handled = true;

				try
				{
					string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
					errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n");

					System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg + "\");");
				}
				catch (Exception)
				{
				}
			}
		}

		/// <summary>
		/// Extracts an integer parameter from the given dictionary of initialization parameters.
		/// </summary>
		/// <param name="parameters">The dictionary of initialization parameters.</param>
		/// <param name="key">The key specifying the parameter to extract.</param>
		/// <returns>The integer parameter, or null if it's not specified.</returns>
		private static int? GetIntParameter(IDictionary<string, string> parameters, string key)
		{
			string str;
			if (parameters.TryGetValue(key, out str))
			{
				int num;
				if (int.TryParse(str, out num))
				{
					return num;
				}
			}
			return null;
		}

		/// <summary>
		/// Extracts an enum parameter from the given dictionary of initialization parameters.
		/// </summary>
		/// <typeparam name="T">The type of the enum.</typeparam>
		/// <param name="parameters">The dictionary of initialization parameters.</param>
		/// <param name="key">The key specifying the parameter to extract.</param>
		/// <returns>The enum parameter, or null if it's not specified.</returns>
		private static Nullable<T> GetEnumParameter<T>(IDictionary<string, string> parameters, string key) where T : struct
		{
			string str;
			if (parameters.TryGetValue(key, out str))
			{
				try
				{
					T value = (T)Enum.Parse(typeof(T), str, true);
					return value;
				}
				catch (ArgumentException)
				{
				}
			}
			return null;
		}
	}
}
